import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Button,
  Menu,
  Modal,
  message,
  Divider,
  Popconfirm,
  Select,
  InputNumber,
  Radio,
  TreeSelect,
  Tag,
  Switch,
  Dropdown,
  Badge,
  Spin,
  Icon,
} from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import moment from 'moment';
import styles from '../search.less';
const { TextArea } = Input;
const FormItem = Form.Item;
const { Option } = Select;
const viewLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 18 },
};
const dbType = ['mysql', 'oracle', 'teledb', 'pgsql'];
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    updateFn,
    handleModalVisible,
    text,
    labelList,
    form: { getFieldValue },
    loadingupdate,
  } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (text) {
        updateFn(fieldsValue, text);
      }
    });
  };

  return (
    <Modal
      destroyOnClose
      width={640}
      title="修改字段"
      visible={modalVisible}
      onOk={okHandle}
      confirmLoading={loadingupdate}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 18 }} label="修改前敏感字段">
        {text.label}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 18 }} label="修改后敏感字段">
        {form.getFieldDecorator('wordIds', {
          rules: [{ required: true, message: '密钥规则不能为空' }],
          initialValue: text && text.wordIds,
        })(
          <Select placeholder="请选择" showSearch style={{ width: '100%' }}>
            <Option value="0">非敏感</Option>
            {labelList &&
              labelList.length &&
              labelList.map(v => {
                return (
                  <Option value={v.wordId} key={v.wordId}>
                    {v.name}
                  </Option>
                );
              })}
          </Select>
        )}
      </FormItem>
    </Modal>
  );
});

/* eslint react/no-multi-comp:0 */
@connect(({ scanColumn, loading }) => ({
  scanColumn,
  loading: loading.effects['scanColumn/queryList'],
  loadingupdate: loading.effects['scanColumn/update'],
}))
@Form.create()
class scanColumn extends PureComponent {
  state = {
    modalVisible: false,
    formValues: {},
    selectedRows: [],
    text: {},
    showSensitiveInfo: true,
    labelList: [],
    databaseList: [],
  };

  columns = [
    // {
    //   title: '数据库类型',
    //   dataIndex: 'dbType',
    //   width:100,
    // },
    {
      title: '数据库名称',
      dataIndex: 'dbName',
    },
    {
      title: '字段类型',
      dataIndex: 'columnType',
    },
    {
      title: '表名',
      dataIndex: 'tableName',
      width: 230,
      ellipsis: 'true',
    },
    {
      title: '列名',
      dataIndex: 'columnName',
    },
    {
      title: '列备注',
      dataIndex: 'columnRemark',
    },
    {
      title: '敏感字段',
      dataIndex: 'label',
      render: text => text && <Tag color="red">{text}</Tag>,
    },
    {
      title: '识别方式',
      dataIndex: 'discernType',
      render: text => <Fragment>{text == 0 ? '自动识别' : '人工确认'}</Fragment>,
    },
    {
      title: '匹配结果',
      dataIndex: 'isApprove',
      render: text => (
        <Fragment>
          {(() => {
            switch (text) {
              case 1:
              case 3:
                return <Badge status="success" text="准确" />;
                break;
              case 2:
                return <Badge status="error" text="不准确" />;
                break;
              default:
                return '--';
            }
          })()}
        </Fragment>
      ),
    },
    {
      title: '采样数据',
      dataIndex: 'remark',
      ellipsis: 'true',
    },
    // {
    //   title: '扫描时间',
    //   dataIndex: 'createTime',
    //   render: text => <Fragment>{moment(text).format('YYYY-MM-DD HH:mm:ss')}</Fragment>,
    //   width:160,
    // },
    {
      title: '操作',
      width: 140,
      render: (text, props) => (
        <Fragment>
          <a onClick={() => this.handleDetailModalVisible(true, text)}>详情</a>
          <Divider type="vertical" />
          <Dropdown
            overlay={
              <Menu onClick={({ key }) => this.setConfirm(key, text.scanResultId, text)}>
                <Menu.Item key="1">准确</Menu.Item>
                <Menu.Item key="2">不准确</Menu.Item>
                <Menu.Item key="0">重置</Menu.Item>
                <Menu.Item key="3">修改</Menu.Item>
              </Menu>
            }
          >
            <a>
              人工确认 <Icon type="down" />
            </a>
          </Dropdown>
        </Fragment>
      ),
    },
  ];

  // 分页查询列表
  pageList(data, pageSize = 10, pageNum = 0) {
    const { dispatch } = this.props;
    const values = {
      dbType: data && data.dbType,
      dbName: data && data.dbName && data.dbName.split(',')[1], //逗号之后为dbName
      dbId: data && data.dbName && data.dbName.split(',')[0],
      tableName: data && data.tableName,
      wordId: data && data.wordId,
      matchNums: this.state.showSensitiveInfo == false ? '' : 0,
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    dispatch({
      type: 'scanColumn/queryList',
      payload: values,
    });
  }

  // 查询敏感级别
  selectLabelList() {
    const { dispatch } = this.props;
    dispatch({
      type: 'scanColumn/selectLabelList',
      callback: res => {
        this.setState({
          labelList: res.data.dataList,
        });
      },
    });
  }

  // 查询数据库
  selectDatabaseList() {
    const { dispatch } = this.props;
    dispatch({
      type: 'scanColumn/selectDatabaseList',
      callback: res => {
        this.setState({
          databaseList: res.data.dataList,
        });
      },
    });
  }

  componentDidMount() {
    this.pageList();
    this.selectLabelList();
    this.selectDatabaseList(); //数据库列表
  }

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      this.setState({
        formValues: fieldsValue,
      });
      //点击查询
      this.pageList(fieldsValue);
    });
  };

  //设置人工确认
  setConfirm = (key, scanResultIds, text) => {
    if (key === '3') this.handleModalVisible(true, text);
    else {
      const { dispatch } = this.props;
      return dispatch({
        type: 'scanColumn/update',
        payload: {
          scanResultIds,
          isApprove: key,
        },
        callback: res => {
          if (res.result == 'ok') {
            Modal.success({ title: res.msg });
            this.pageList();
          } else {
            Modal.error({ title: '操作失败', content: res.msg });
          }
        }, //callback
      });
    }
  };

  //批量设置人工确认
  setConfirms = (key, rows = []) => {
    const ids = rows.map(item => {
      return item.scanResultId;
    });
    // const key = e.target.value;
    this.setConfirm(key, ids);
  };

  // 修改弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text: text,
    });
  };

  // 修改接口
  updateFn = (fields, text) => {
    const { dispatch } = this.props;
    const params = {
      scanResultId: text.scanResultId,
      wordIds: fields.wordIds,
      isApprove: 3,
    };
    dispatch({
      type: 'scanColumn/update',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          // form.resetFields();
          this.handleModalVisible();
          this.pageList();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  };

  // 详情
  handleDetailModalVisible = (flag, text) => {
    this.setState({
      detailModalVisible: !!flag,
      detailsData: text,
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置

  switchChange = checked => {
    this.setState({ showSensitiveInfo: checked }, () => {
      this.pageList();
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { labelList, databaseList } = this.state;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="数据库类型">
              {getFieldDecorator('dbType')(
                <Select placeholder="请选择" allowClear>
                  <Option value="">全部</Option>
                  {dbType.map(item => (
                    <Option value={item}>{item}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="数据库名称">
              {/* {getFieldDecorator('dbName')(<Input placeholder="请输入" />)} */}
              {getFieldDecorator('dbName')(
                <Select
                  placeholder="请选择"
                  allowClear
                  // onFocus={()=>this.selectDatabaseList()}
                  // loading={this.props.loadingselectDatabaseList}
                >
                  <Option value="">全部</Option>
                  {databaseList &&
                    databaseList.length &&
                    databaseList.map(v => {
                      return (
                        <Option value={`${v.dbId},${v.dbName}`} key={v.dbId}>
                          {v.dbName}
                        </Option>
                      );
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="表名">
              {getFieldDecorator('tableName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="&nbsp;&nbsp;&nbsp;&nbsp;敏感字段">
              {getFieldDecorator('wordId')(
                <Select placeholder="请选择" showSearch allowClear>
                  <Option value="">全部</Option>
                  {labelList &&
                    labelList.length &&
                    labelList.map(v => {
                      return (
                        <Option value={v.wordId} key={v.wordId}>
                          {v.name}
                        </Option>
                      );
                    })}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  handleStandardTableChange(pagination, filters, sorter) {
    const { formValues } = this.state;
    // 分页请求
    this.pageList(formValues, pagination.pageSize, pagination.current - 1);
  }

  render() {
    const {
      scanColumn: { data },
      loading,
      loadingupdate,
    } = this.props;
    const {
      selectedRows,
      modalVisible,
      text,
      detailModalVisible,
      detailsData,
      labelList,
    } = this.state;
    const detailsMethods = {
      handleDetailModalVisible: this.handleDetailModalVisible,
    };
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      updateFn: this.updateFn,
    };
    return (
      <Fragment>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <Switch
              checkedChildren="仅含敏感数据"
              unCheckedChildren="所有数据"
              onChange={this.switchChange}
              checked={this.state.showSensitiveInfo}
              style={{ marginBottom: 16 }}
            />
            <br />
            <div className={styles.tableListOperator}>
              {this.state.selectedRows.length > 0 && (
                <span>
                  <Button onClick={() => this.setConfirms(1, selectedRows)} type="primary">
                    正确
                  </Button>
                  <Button onClick={() => this.setConfirms(2, selectedRows)} type="primary">
                    不正确
                  </Button>
                  <Button onClick={() => this.setConfirms(0, selectedRows)} type="primary">
                    重置
                  </Button>
                </span>
              )}
            </div>
            <TableList
              className={styles.tdPadding}
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              columns={this.columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange.bind(this)}
              rowKey={record => record.scanResultId}
              // hideRowSelection
            />
          </div>
        </Card>
        {text && (
          <CreateForm
            {...parentMethods}
            modalVisible={modalVisible}
            text={text}
            loadingupdate={loadingupdate}
            labelList={labelList}
          />
        )}

        {detailModalVisible ? (
          <Details
            {...detailsMethods}
            detailModalVisible={detailModalVisible}
            detailsData={detailsData}
          />
        ) : null}
      </Fragment>
    );
  }
}

//查看详情弹窗
class Details extends PureComponent {
  render() {
    const { detailModalVisible, handleDetailModalVisible, detailsData } = this.props;
    return (
      <Modal
        destroyOnClose
        width={800}
        title="查看详情"
        visible={detailModalVisible}
        onCancel={() => handleDetailModalVisible(false)}
        footer={[
          <Button key="back" type="primary" onClick={() => handleDetailModalVisible()}>
            返回
          </Button>,
        ]}
        className={styles.viewMore}
      >
        <Row>
          <Col md={12}>
            <FormItem {...viewLayout} label="数据库类型">
              {detailsData.dbType}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...viewLayout} label="数据库名称">
              {detailsData.dbName}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...viewLayout} label="表名">
              {detailsData.tableName}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...viewLayout} label="列名">
              {detailsData.columnName}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...viewLayout} label="列备注">
              {detailsData.columnRemark}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...viewLayout} label="敏感字段">
              {detailsData.label}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...viewLayout} label="识别方式">
              {detailsData.discernType == 0 ? '自动识别' : '人工确认'}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...viewLayout} label="匹配结果">
              {(() => {
                switch (detailsData.isApprove) {
                  case 1:
                  case 3:
                    return '准确';
                    break;
                  case 2:
                    return '不准确';
                    break;
                  default:
                    return '--';
                }
              })()}
            </FormItem>
          </Col>
          <Col md={12}>
            <FormItem {...viewLayout} label="采样数据">
              {detailsData.remark}
            </FormItem>
          </Col>

          <Col md={12}>
            <FormItem {...viewLayout} label="扫描时间">
              {moment(detailsData.createTime).format('YYYY-MM-DD HH:mm:ss')}
            </FormItem>
          </Col>
        </Row>
      </Modal>
    );
  }
}
export default scanColumn;

const loopTree = data => {
  return data.map(item => {
    if (item.children) {
      return (
        <TreeSelect.TreeNode value={item.typeCode} title={`${item.typeCode}${item.typeName}`}>
          {loopTree(item.children)}
        </TreeSelect.TreeNode>
      );
    }
    return <TreeSelect.TreeNode value={item.typeCode} title={`${item.typeCode}${item.typeName}`} />;
  });
};
